package pack;

import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.ejb.EJB;
import javax.faces.application.ConfigurableNavigationHandler;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.SessionScoped;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;

import dao.CarteDAORemote;
import dao.EmployeeDAORemote;
import dao.ListaDAORemote;
import dto.CarteDTO;
import dto.EmployeeDTO;
import dto.ListaDTO;

@ManagedBean(name = "carteBean")
@SessionScoped
public class CartiBean implements Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	@EJB
	CarteDAORemote carteDAO;
	
	@EJB
	ListaDAORemote listaDAO;
	
	@EJB
	EmployeeDAORemote employeeDAO;

	
	@ManagedProperty(value = "#{carteDTO}")
	private CarteDTO carteDTO;
	
	@ManagedProperty(value = "#{listaDTO}")
	private ListaDTO listaDTO;

	
	EmailBean email = new EmailBean();
	

	ExternalContext exCon;
	private int id;

	private String nume;

	private String autor;

	private String anul;

	private String status;

	private String data_retur;

	private String imprumatata_de;
	
	List<CarteDTO> carti;
	
	
	
	private int del;
	
	private int upd;
	
	private String ce;
	
	private String lace;
	
	private String optiune;
	
	private CarteDTO cartiUpd;
	
	boolean editable;

	private int angId;
	
	private String dupa;
	
	private String valoare;
	
	public void verify(){
		FacesContext fc = FacesContext.getCurrentInstance();
		EmployeeDTO eDTO = (EmployeeDTO)fc.getExternalContext().getSessionMap().get("loggedInUser");
		
		ConfigurableNavigationHandler nav 
			= (ConfigurableNavigationHandler) 
		fc.getApplication().getNavigationHandler();
		
		if (eDTO != null){
			if (eDTO.getRank() != 5){
				nav.performNavigation("home.xhtml");
			}
		}
		else {
			nav.performNavigation("home.xhtml");
		}
		filtru();
		//read();
	}
	
	public void verifyA(){
		FacesContext fc = FacesContext.getCurrentInstance();
		EmployeeDTO eDTO = (EmployeeDTO)fc.getExternalContext().getSessionMap().get("loggedInUser");
		
		ConfigurableNavigationHandler nav 
			= (ConfigurableNavigationHandler) 
		fc.getApplication().getNavigationHandler();
		
		if (eDTO != null){
			if (eDTO.getRank() != 1){
				nav.performNavigation("home.xhtml");
			}
		}
		else {
			nav.performNavigation("home.xhtml");
		}
		read();
	}
	
	public String imprumuta(CarteDTO carte){
		if (carte.getStatus().equals("Disponibil")){
			Date d = new Date();
			SimpleDateFormat dformat =
				    new SimpleDateFormat("yyyy-MM-dd");
			String dd = dformat.format(d);
			FacesContext fc = FacesContext.getCurrentInstance();
			EmployeeDTO eDTO = (EmployeeDTO)fc.getExternalContext().getSessionMap().get("loggedInUser");
			ListaDTO lista = new ListaDTO();
			lista.setId_angajat(eDTO.getId());
			lista.setId_carte(carte.getId());
			lista.setData(plus2Weeks(dd));
			lista.setActiv("Activ");
			lista.setNume(eDTO.getLastname());
			lista.setPrenume(eDTO.getFirstname());
			lista.setTitlu(carte.getNume());
			try {
				listaDAO.addCarte(lista);
			} catch (Exception exc) {
				exc.printStackTrace();
			}
			
			
			
		}
		else if (carte.getStatus().equals("Imprumutat")){
			FacesContext fc = FacesContext.getCurrentInstance();
			EmployeeDTO eDTO = (EmployeeDTO)fc.getExternalContext().getSessionMap().get("loggedInUser");
			ListaDTO lista = new ListaDTO();
			lista.setId_angajat(eDTO.getId());
			lista.setId_carte(carte.getId());
			String d = carte.getData_retur();
			lista.setData(plus2Weeks(d));
			lista.setActiv("Activ");
			lista.setNume(eDTO.getLastname());
			lista.setPrenume(eDTO.getFirstname());
			lista.setTitlu(carte.getNume());
			try {
				listaDAO.addCarte(lista);
			} catch (Exception exc) {
				exc.printStackTrace();
			}
		}
		FacesContext fc = FacesContext.getCurrentInstance();
		EmployeeDTO eDTO = (EmployeeDTO)fc.getExternalContext().getSessionMap().get("loggedInUser");
		String to = employeeDAO.findAdminEmail();
		String from = eDTO.getEmail();
		String subject = "Book request!";
		String msg = "Hi " + "Administrator" + "!\n\n" 
				+ eDTO.getFirstname() + " " + eDTO.getLastname()
				+ " wants to borrow a book from library: "
				+ carte.getNume() + ".\n\n"
				+ "Please respond as quick as you can...";
		email.sendMail(from, to, subject, msg);
		return "";
	}
	
	public String edit(CarteDTO c){
		setCartiUpd(c);
		return "cartiUpdate";
	}
	
	
	

	public void resetFields(){
		setAnul("");
		setAutor("");
		setData_retur("");
		setImprumatata_de("");
		setNume("");
		setStatus("Disponibil");
	}
	
	public String create(){
		CarteDTO carteDTO = new CarteDTO();
		carteDTO.setNume(getNume());
		carteDTO.setAnul(getAnul());
		carteDTO.setAutor(getAutor());
		carteDTO.setImprumutata_de("-");
		carteDTO.setStatus(getStatus()); 
		carteDTO.setData_retur(getData_retur());
		carteDAO.add(carteDTO);
		
		resetFields();
		
		return "";
	}
	
	public String read(){
		carti = carteDAO.findAllBooks();
		this.setCarti(carti);
		return "";
	}
	
	public String delete(CarteDTO carte){
		carteDAO.del(carte);
		return "";
	}
	
	public String update(CarteDTO c){
		carteDAO.update(c);
		read();
		return "";
	}
	
	public String filtru(){
		read();
		if ("Titlu".equals(getDupa()))
			setCarti(carteDAO.getCarteDupa(getDupa(), getValoare()));
		else if ("Autor".equals(getDupa()))
			setCarti(carteDAO.getCarteDupa(getDupa(), getValoare()));
		else if ("Status".equals(getDupa()))
			setCarti(carteDAO.getCarteDupa(getDupa(), getValoare()));
		else if ("Anul".equals(getDupa()))
			setCarti(carteDAO.getCarteDupa(getDupa(), getValoare()));
		else{
			setCarti(carteDAO.findAllBooks());
		}
			
		return "";
	}
	
	public String faOptiune(){
		FacesContext fc = FacesContext.getCurrentInstance();
		if (getOptiune().equals("Imprumutare")){
			EmployeeDTO e = (EmployeeDTO)fc.getExternalContext().getSessionMap().get("loggedInUser");
			carteDAO.imprumutare(getId(), e);
		}
		if (getOptiune().equals("Returnare")){
			EmployeeDTO e = (EmployeeDTO)fc.getExternalContext().getSessionMap().get("loggedInUser");
			carteDAO.returnare(getId(), e);
		}
		if (getOptiune().equals("Recenzii")){
			
		}
		if (getOptiune().equals("Sugestii")){
			
		}
		if (getOptiune().equals("Revizuire")){
			
		}		
		//read();
		return "";
	}
	
	public String plus2Weeks(String d){
		// format: yyyy-mm-dd
		String z = "";
		z = z + d.charAt(8) + d.charAt(9);
		String l = "";
		l = l + d.charAt(5) + d.charAt(6);
		String a = "";
		a = a + d.charAt(0) + d.charAt(1) + d.charAt(2) + d.charAt(3);
		int zi = Integer.parseInt(z);
		int lu = Integer.parseInt(l);
		int an = Integer.parseInt(a);
		if (lu == 2){
			if (zi > 14){
				zi = zi + 14 - 28;
				lu = lu + 1;
			}
			else
				zi = zi + 14;
		}
		else if (lu == 4 || lu == 6 || lu == 9 || lu == 11){
			if (zi > 16){
				zi = zi + 14 - 30;
				lu = lu + 1;
			}
			else
				zi = zi + 14;
		}
		else{
			if (zi > 17){
				zi = zi + 14 - 31;
				lu = lu + 1;
			}
			else
				zi = zi + 14;
		}
		if (lu == 13){
			lu = 1;
			an = an + 1;
		}
		//System.out.println("An: " + an + " Lu: " + lu + " Zi: " + zi);
		String re = String.valueOf(an);
		re = re + "-" + String.valueOf(lu) + "-" + String.valueOf(zi);
		return re;
	}
	
	

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getNume() {
		return nume;
	}

	public void setNume(String nume) {
		this.nume = nume;
	}

	public String getAutor() {
		return autor;
	}

	public void setAutor(String autor) {
		this.autor = autor;
	}

	public String getAnul() {
		return anul;
	}

	public void setAnul(String anul) {
		this.anul = anul;
	}

	public String getStatus() {
		return status;
	}

	public void setStatus(String status) {
		this.status = status;
	}

	public String getData_retur() {
		return data_retur;
	}

	public void setData_retur(String data_retur) {
		this.data_retur = data_retur;
	}

	public String getImprumatata_de() {
		return imprumatata_de;
	}

	public void setImprumatata_de(String imprumatata_de) {
		this.imprumatata_de = imprumatata_de;
	}
	public CarteDTO getCarteDTO() {
		return carteDTO;
	}

	public void setCarteDTO(CarteDTO carteDTO) {
		this.carteDTO = carteDTO;
	}
	
	public List<CarteDTO> getCarti() {
		return carti;
	}

	public void setCarti(List<CarteDTO> carti) {
		this.carti = carti;
	}

	public int getDel() {
		return del;
	}

	public void setDel(int del) {
		this.del = del;
	}

	public int getUpd() {
		return upd;
	}

	public void setUpd(int upd) {
		this.upd = upd;
	}

	public String getCe() {
		return ce;
	}

	public void setCe(String ce) {
		this.ce = ce;
	}

	public String getLace() {
		return lace;
	}

	public void setLace(String lace) {
		this.lace = lace;
	}

	public String getOptiune() {
		return optiune;
	}

	public void setOptiune(String optiune) {
		this.optiune = optiune;
	}
	
	public int getAngId() {
		return angId;
	}

	public void setAngId(int angId) {
		this.angId = angId;
	}

	public boolean isEditable() {
		return editable;
	}

	public void setEditable(boolean editable) {
		this.editable = editable;
	}
	
	public ListaDTO getListaDTO() {
		return listaDTO;
	}

	public void setListaDTO(ListaDTO listaDTO) {
		this.listaDTO = listaDTO;
	}

	public CarteDTO getCartiUpd() {
		return cartiUpd;
	}

	public void setCartiUpd(CarteDTO cartiUpd) {
		this.cartiUpd = cartiUpd;
	}

	public String getDupa() {
		return dupa;
	}

	public void setDupa(String dupa) {
		this.dupa = dupa;
	}

	public String getValoare() {
		return valoare;
	}

	public void setValoare(String valoare) {
		this.valoare = valoare;
	}

}
